import axios from 'axios'
import Cookies from 'js-cookie'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    // 优先从Cookie获取token，然后从localStorage获取
    const token = Cookies.get('token') || localStorage.getItem('token')
    if (token) {
      config.headers.token = token // 根据后端代码，使用token作为header字段
    }
    
    // 详细的请求日志
    console.log('=== 请求详情 ===', {
      method: config.method,
      url: config.url,
      baseURL: config.baseURL,
      fullURL: (config.baseURL || '') + (config.url || ''),
      isFormData: config.data instanceof FormData,
      hasToken: !!token,
      headers: config.headers
    })
    
    // 如果是FormData，确保不设置Content-Type，让浏览器自动设置
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type']
      console.log('🔄 FormData上传请求:', {
        url: config.url,
        method: config.method,
        baseURL: config.baseURL,
        计算的完整URL: (config.baseURL || '') + (config.url || ''),
        hasToken: !!token,
        token: token ? token.substring(0, 20) + '...' : 'none',
        formDataKeys: Array.from(config.data.keys()),
        formDataValues: Array.from(config.data.values()).map(v => 
          v instanceof File ? `File(${v.name}, ${v.size}bytes)` : v
        )
      })
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一处理响应
api.interceptors.response.use(
  (response) => {
    console.log('API响应:', response.config.url, response.data)
    return response // 保持返回完整的response对象
  },
  (error) => {
    console.error('API错误:', error)
    
    // 只有在用户相关的API出现401错误时才跳转到登录页
    // 管理员API的401错误不应该导致用户退出
    if (error.response?.status === 401) {
      const url = error.config?.url || ''
      // 只有在用户API（/User路径）出现401时才视为登录过期
      if (url.includes('/User/')) {
        console.log('用户API返回401，可能是登录过期')
        // 清除过期token，跳转登录
        Cookies.remove('token')
        Cookies.remove('userInfo')
        Cookies.remove('userType')
        localStorage.removeItem('token')
        window.location.href = '/login'
      } else {
        console.log('管理员API返回401，这是正常的权限控制')
      }
    }
    throw error
  }
)

// API包装函数，处理响应并返回BaseResponse
const apiWrapper = {
  async get(url) {
    const response = await api.get(url)
    const res = response.data
    if (res.code === 0) {
      return res
    } else {
      throw new Error(res.message || '请求失败')
    }
  },

  async post(url, data, config = {}) {
    const response = await api.post(url, data, config)
    const res = response.data
    if (res.code === 0) {
      return res
    } else {
      throw new Error(res.message || '请求失败')
    }
  },

  async put(url, data) {
    const response = await api.put(url, data)
    const res = response.data
    if (res.code === 0) {
      return res
    } else {
      throw new Error(res.message || '请求失败')
    }
  },

  async delete(url) {
    const response = await api.delete(url)
    const res = response.data
    if (res.code === 0) {
      return res
    } else {
      throw new Error(res.message || '请求失败')
    }
  },
}

export { api, apiWrapper }
export default api 